iT邦幫忙

2023 iThome 鐵人賽

DAY 21
0
Web 3

I have an AI ,I have a React, Ugh ,AI -React 系列 第 21

[Day21] 要放假了 今晚吃什麼

  • 分享至 

  • xImage
  •  

咒語 用 mui 寫一個頁面 來決定吃甚麼 先給十筆台灣常見的假資料 並且可以有個輸入 幫我算出各項百分比 要依據輸入變動

import React, { useState, useEffect } from "react";
import { Button, TextField, Typography, Container, Grid } from "@mui/material";

function Roulette() {
  const [foodList, setFoodList] = useState([
    "牛肉麵",
    "滷肉飯",
    "排骨便當",
    "拉麵",
    "披薩",
    "炸雞",
    "壽司",
    "炒麵",
    "三明治",
    "鍋貼",
  ]);
  const [newFood, setNewFood] = useState("");
  const [selectedFood, setSelectedFood] = useState(null);

  // 計算總食物項數量
  const totalFoodCount = foodList.length;

  // 計算每個食物項的百分比
  const foodPercentages = foodList.map(() => (1 / totalFoodCount) * 100);

  const handleAddFood = () => {
    if (newFood.trim() !== "") {
      setFoodList([...foodList, newFood]);
      setNewFood("");
    }
  };

  const handleRandomSelection = () => {
    const randomIndex = Math.floor(Math.random() * foodList.length);
    setSelectedFood(foodList[randomIndex]);
  };

  return (
    <Container>
      <Typography variant="h4" align="center" gutterBottom>
        食物輪盤
      </Typography>
      <Grid container spacing={2}>
        <Grid item xs={12} sm={6}>
          <TextField
            label="輸入新食物"
            variant="outlined"
            fullWidth
            value={newFood}
            onChange={(e) => setNewFood(e.target.value)}
          />
        </Grid>
        <Grid item xs={12} sm={6}>
          <Button
            variant="contained"
            color="primary"
            onClick={handleAddFood}
            fullWidth
          >
            添加食物
          </Button>
        </Grid>
      </Grid>
      <div style={{ marginTop: "20px" }}>
        <Button
          variant="contained"
          color="primary"
          onClick={handleRandomSelection}
        >
          隨機選擇食物
        </Button>
      </div>
      {selectedFood && (
        <Typography variant="h5" align="center" style={{ marginTop: "20px" }}>
          今天吃:{selectedFood}
        </Typography>
      )}
      <Typography variant="h6" style={{ marginTop: "20px" }}>
        各食物百分比:
      </Typography>
      <ul>
        {foodList.map((food, index) => (
          <li key={index}>
            {food}: {foodPercentages[index].toFixed(2)}%
          </li>
        ))}
      </ul>
    </Container>
  );
}

export default Roulette;

這樣就可以決定今晚吃啥了 祝各位放假愉快


上一篇
[Day20] 新版navbar
下一篇
[Day22] 放假了 要出遊 來做個任務列表吧
系列文
I have an AI ,I have a React, Ugh ,AI -React 30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言